var app = getApp();
import {
  api,
  util,
  dialog,
  clickIncrement,
  clearIncrement
} from '../../../../js/util'
import {
  router
} from '../../../../js/router'
import {
  cart
} from "../../../../js/modules/order.js"
import {
  coupon
} from '../../../../js/modules/market';
import { list} from "../../../../js/modules/mall.js";
import authorize from '../../../../js/modules/authorize.js'
import BasePage from '../../../../js/common/base-page'
import { hideTabbar } from '../../../../js/compatible';
import { alert, confirm, deepClone, isEmpty } from '../../../../js/newUtil';
import { calulateAdd, calulateReduce, precisionX, precisionDiv } from '../../../../js/common/math';

BasePage({
  pageKey:"cart",
  validateLogin: app.dns.fkId != app.dns.proprietorId,
  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    cartlist: [],
    current_coupons: [],
    caculate_info: {
      quantity: 0
    },
    select_all_status: false,
    isLoadComplete: false,
    isExcuting:false,
    isSelecting:false,
    quantityDigits:0,
    priceDigits:2,
    cart_dic:{},
    totalPage: 0,
    pageSize: 20,
    pageIndex: 1,
    loopCount:0,
    visitTimer:null,
    ruleTypeTotalPrice: 0,
    ruleTypeTotalNum: 0,
    isIphoneX:app.globalData.isIphoneX,
    mainColor:'',//主题色
    Currency:'',//货币符号
    CartName:'',//购物车名称显示
    tabindex:-1,
    curPath:'',
    chooseGiftIndex: [-1, -1, -1, -1], // 当前选择赠品所点击的数据的index
    selectedGift: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu();//隐藏分享
    app.initTabBar();
    console.log('cart');
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  loadList: function () {
    var that = this;
    let data={
      quantityDigits: this.data.quantityDigits,
      areaCode: this.data.areaCode,
      Currency: this.data.Currency
    }
    cart.loadList(data,function (source) {
      //计算总页数
      let totalCount = 0;
      if(source && source.length > 0){
        for (let i = 0; i < source.length; i++) {
          let seller = source[i];
          if(seller.PromotRules && seller.PromotRules.length > 0){
            for (let j = 0; j < seller.PromotRules.length; j++) {
              let rule = seller.PromotRules[j];
              if(rule.Products && rule.Products.length > 0){
                totalCount += rule.Products.length;
              }
            }
          }
        }
      }
      var cart_dic=cart.reset_cart_dic(source)
      that.setData({
        cart_dic: cart_dic,
        totalPage: totalCount <= that.data.pageSize ? 1 : Math.ceil(totalCount/that.data.pageSize)
      });
      source = that.resetProductInfo(source)
      that.data.cartlist = source;
      let AreaId = that.data.areaCode || ''
      //加载促销信息
      cart.loadPromotions(source, cart_dic, AreaId,function(content) {
        content = that.resetProductInfo(content)
        that.setData({
          isLoadComplete: true,
          caculate_info: cart.caculate_info(content),
          cartlist: content
        });
        that.set_select_all_status(that);
        //加载赠品
        cart.loadGifts(source, cart_dic, function (content) {
          content.forEach(function(item){
            item.PromotRules.forEach(function(rule){
              rule.Nums = 0;
              rule.Products.forEach(function(p){
                rule.ZeroStockBuy = p.ZeroStockBuy;
                rule.PurchasePower = p.PurchasePower;
                p.Goods.forEach(function(g){
                  rule.Stock = g.Stock;
                  rule.Shelved = g.Shelved;
                  rule.BuyLowerLimit = g.BuyLowerLimit;
                  if(rule.RuleType == 5){
                    rule.Nums ++;
                    g.IsChecked = rule.Checked;
                  }
                })
              })
            })
          })
          let cartlist = that.resetProductInfo(content)
          that.setData({
            cartlist: cartlist
          });
          console.log(cartlist)
          // 计算单个list RuleType=5的商品总价
          that.getGoodsTotalPrice(5)
        });
      });
      //加载优惠券
      that.load_coupons();
    });
  },
  /**获得全选状态 */
  set_select_all_status: function(that) {
    var num = 0;
    var source = that.data.cartlist;
    source.map(function (seller, i) {
      seller.PromotRules.map(function (rule, j) {
        rule.Products.map(function (p, k) {
          p.Goods.map(function (g, l) {
            if (g.IsChecked != 1) num++;
          });
        });
      });
    });
    that.setData({
      select_all_status: source.length>0&&num<1
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //隐藏原生底部导航
    // let pages = getCurrentPages();
    // let curPage = pages[pages.length-1];
    // let curPath = curPage.__route__;
    // if(curPath.indexOf('/')!=0){
    //   curPath = '/'+curPath;
    // }
    // app.initTabBar();
    hideTabbar()
    var tabindex = app.getTabBarindex();
    this.setData({
      tabindex:tabindex
      // curPath:curPath
    })
    this.isCanVisit(()=>{
      this.getWholesaleConfig();
      if (!authorize.isLogin("store")) {
        this.setData({
          isLoadComplete:true
        })
        return;
      }
      this.setData({
        mainColor:api.titleColor||"#e56b14",
        Currency:api.Currency || '￥'
      })
      this.data.isExcuting=false;
    })
    
  },
  isCanVisit(callback){
    let that = this;
    this.clearVisitTimer();
    this.data.visitTimer = setTimeout(()=>{
      if(api.isLoginVisit!=undefined){
        that.data.loopCount = 0;
        if ((app.dns.fkFlag != app.dns.proprietor && app.dns.fkId > 0 && app.dns.proprietorId == 0 && !authorize.isLogin('store')) || (api.isLoginVisit&&!authorize.isLogin('store'))) {
          authorize.redirect('store');
        }else{
          callback();
        }
      }else if (that.data.loopCount < 60) {
        that.data.loopCount++;
        that.isCanVisit(callback);
      }
    }, 100)
  },
  clearVisitTimer(){
    if (this.data.visitTimer!=null) {
      clearTimeout(this.data.visitTimer);
      this.data.visitTimer = null;
    }
  },
  /**加载商品类的配置项参数 */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    list.getWholesaleConfigs(
      fkid,
      fkflag,
       (content)=> {
         console.log(content.CartName,'=========')
        that.setData({
          quantityDigits: content.QuantityDigits,
          priceDigits: content.PriceDigits,
          addressAssignDepot: content.AddressAssignDepot,
          CartName:api.CartName || '购物车'
        });
        wx.setNavigationBarTitle({
          title:api.CartName || '购物车'
        })
        if (content.AddressAssignDepot){
          this.selectComponent("#deliveryComponent").getDefaultAddress();
        }
        else{
          if(authorize.isLogin("store")){
            this.selectedAdress({ detail: { Area: "", Code: "" } });
          }
        }
       
      });
  },
  /**
   * 加载优惠券
   */
  load_coupons: function() {
    var that = this;
    if (that.data.cartlist==undefined || that.data.cartlist.length==0) return;
    var current = that.data.cartlist[0];
    if(current==undefined) return;
    cart.loadCoupons([current], that.data.cart_dic, function(content) {
      for (var i = 0; i < content.length; i++) {
        content[i].PullMaxCount = parseInt(content[i].PullMaxCount);
        content[i].DrawCount = parseInt(content[i].DrawCount);
        content[i].PullCount = parseInt(content[i].PullCount);
        coupon.praseCouponStatus(content[i], "hasget","已领取");
      }
      that.setData({
        current_coupons: content
      });
    });

  },
  /**
   * 显示优惠券
   *  */
  showCoupons: function(e) {
    var that = this;
    dialog.showModal(that, 'showModalStatus')
  },
  /**
   * 领取优惠券
   */
  onlineReceivedCoupon: async function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var current = this.data.current_coupons[index];
    var couponId = current.CouponId
    var fromFkId = current.FKId;
    let type = e.currentTarget.dataset.type
    let integration = e.currentTarget.dataset.integration
    if (type == 5) {
      // 积分兑换时，需要用户二次确认是否消耗积分兑换
      let confirmRes = await confirm({
        content: `请确认是否需要使用${integration}积分兑换该优惠券，兑换后积分不会退还，是否兑换？`
      })
      if (!confirmRes.confirm) {
        return
      }
    }
    coupon.onlineReceivedCoupon(couponId, fromFkId, function() {
      //dialog.hideModal(that, 'showModalStatus')
      that.data.current_coupons[index].PullCount = current.PullCount + 1;
      that.data.current_coupons[index].IsAgainPull=0;
      coupon.praseCouponStatus(that.data.current_coupons[index], "hasget", "已领取");
      that.setData({
        current_coupons: that.data.current_coupons
      });
    });
  },
  /**
   * 移除购物车
   */
  onRemoveCartEvent: function(e) {
    var that = this;
    clickIncrement(function() {
      cart.delSingleCart(that.data.cartlist, e.detail.id,that.data.CartName, function(content) {
        that.loadList();
      });
    });
  },
  /**
   * 批量移除
   */
  onRemoveAllCartEvent(){
    var that=this;
    var source = that.data.cartlist;
    var goodsId=[];
    source.map(function (seller, i) {
      seller.PromotRules.map(function (rule, j) {
        rule.Products.map(function (p, k) {
          p.Goods.map(function (g, l) {
            if (g.IsChecked == 1) goodsId.push(g.Id);
          });
        });
      });
    });
    clickIncrement(function () {
      cart.delCart(that.data.cartlist, goodsId, that.data.CartName,function (content) {
        that.loadList()
      });
    });
  },
  /**
   * 单个选择事件
   */
  onSelectSingleEvent: function(e) {
    var that = this;
    if (that.data.isExcuting) {
      that.setData({
        cartlist: that.data.cartlist
      });
    };
    that.setData({
      isExcuting: true
    });
    var id = e.currentTarget.dataset.id;
    var checked = e.currentTarget.dataset.checked;
    cart.singleCheckStatus(that.data.cartlist, id, (checked == 1 ? 0 : 1),function (content) {
      content = that.resetProductInfo(content, id)
      that.setData({
        caculate_info: cart.caculate_info(content),
        cartlist: content,
        isExcuting: false
      });
      that.set_select_all_status(that);
    }, function (content) {
      content = that.resetProductInfo(content)
      that.setData({
        cartlist: content,
        isExcuting: false
      });
    });
  },
  /**
   * 全选事件
   */
  onSelectAllEvent: function(e) {
    var that = this;
    if (that.data.isSelecting) return;
    that.setData({
      isSelecting: true
    });
    that.data.select_all_status = (that.data.select_all_status == 1 ? 0 : 1);
    cart.selectAllStatus(that.data.cartlist, that.data.select_all_status, function (content) {
      content = that.resetProductInfo(content)
      content.forEach(function(item){
        item.PromotRules.forEach(function(r){
          if(r.RuleType == 5){
            r.Checked = that.data.select_all_status
            let products = r.Products
            for(let k = 0; k < products.length; k++){
              let goods = products[k].Goods
              for(let l = 0; l < goods.length; l++){
                if(goods[l].IsBuy){
                  goods[l].IsChecked = that.data.select_all_status
                }
              }
            }
          }
        })
      })
      that.setData({
        select_all_status: that.data.select_all_status,
        caculate_info: cart.caculate_info(content),
        cartlist: content,
        isSelecting: false
      });

    }, function (content) {
      content = that.resetProductInfo(content)
      that.setData({
        cartlist: content,
        isSelecting: false
      });
    });
  },
  /**
   * 数量改变
   */
  onNumChage: function(e) {
    var that = this;
    var goodsId = e.detail.primaryId;
    var num = e.detail.value;    
    if (that.data.isExcuting) return;
    that.setData({
      isExcuting: true
    });
    let cartlist = that.data.cartlist
    cart.update_cart_num(cartlist, goodsId, num, this.data.quantityDigits, function (content) {
      cartlist = that.resetProductInfo(cartlist, goodsId)
      that.setData({
        cartlist: content,
        caculate_info: cart.caculate_info(cartlist),
        isExcuting: false
      }, function () {
        that.deleteGift(cartlist)
      });
    }, function () {
      cartlist = that.resetProductInfo(cartlist)
      that.setData({
        caculate_info: cart.caculate_info(cartlist),
        cartlist: cartlist,
        isExcuting: false
      }, function () {
        that.deleteGift(cartlist)
      });
    });
  },
  /**
   * 提交订单
   */
  onSubmitOrder: function(e) {
    var that = this;
    // console.log(this.data.cartlist,'========0');
    cart.submitOrder(this.data.cartlist, this.data.selectedGift, function(content) {
      let cartlist = that.resetProductInfo(content)
      that.setData({
        caculate_info: cart.caculate_info(cartlist),
        cartlist: cartlist
      });
    });
  },
  /**
   * 当切换商品信息后，如果没有选赠品按钮，则删除对应的赠品信息
   * @param {*} cartlist 
   */
  deleteGift(cartlist) {
    let that = this
    let selectedGift = that.data.selectedGift || {}
    cartlist.map((seller) => {
      let PromotRules = seller.PromotRules || []
      PromotRules.map((rule) => {
        let hide = true // 是否已隐藏赠品按钮
        let PromotionType = 1 // 促销类型， 1单品促销 2组合促销
        // 存在rule.Promotion时，为组合促销
        if (rule.info && rule.Promotion) {
          PromotionType = rule.Promotion.PromotionType
          if (rule.info.showChooseProductGift && rule.Promotion.PromotionType == 2) {
            hide = false
          }
        }
        let Products = rule.Products || []
        Products.map((product) => {
          let Goods = product.Goods || []
          Goods.map((good) => {
            // 存在good.Promotion时，为单品促销
            if (good.info && good.Promotion) {
              PromotionType = good.Promotion.PromotionType
              if (good.info.showChooseProductGift && good.Promotion.PromotionType == 1) {
                hide = false
              }
            }
            let key = ''
            if (PromotionType == 1) {
              // 单品促销，赠品数据的key
              key = `${good.Id}_${good.RuleId}_${good.GoodsId}`
            } else {
              // 组合促销，赠品数据的key
              key = `${good.Id}_${rule.RuleId}_0`
            }
            // 当已存在礼物信息，并且未显示赠品按钮时，则删除对应的礼物信息
            if (hide && !isEmpty(selectedGift[key])) {
              delete selectedGift[key]
            }
          })
        })
      })
    })
    that.setData({
      selectedGift
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearIncrement();
    this.data.loopCount = 0;
    this.clearVisitTimer();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.stopPullDownRefresh();
    this.loadList();
    cart.get_cart_count();
    //console.log("onPullDownRefresh");
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let {pageIndex,totalPage} = this.data;
    if(pageIndex < totalPage){
      this.setData({
        pageIndex: pageIndex + 1
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 隐藏遮罩层
   */
  hideModal: function() {
    dialog.hideModal(this, 'showModalStatus')
  },
  /**
 * 促销活动跳转
 */
  onSkipDetail(e) {
    var id = e.currentTarget.id
    router.navigate({
      path: "promotionDetail",
      params: {
        id: id
      }
    })
  },
  selectedAdress(e) {
    let areaCode = e.detail.Code;
    this.data.areaCode = areaCode;
    this.loadList();
    //获取购物车数量
    cart.get_cart_count();
  },
  preventTouchMove() {

  },
  inputBuyNumber(e){
    // console.log('========', e)
    const _this = this
    const reg = /^[0-9]*$/
    let list = _this.data.cartlist
    let pIndex = e.currentTarget.dataset.pindex
    let index = e.currentTarget.dataset.index
    let type = e.currentTarget.dataset.type
    let id = e.currentTarget.dataset.id;
    let maxBuyNum = list[pIndex].PromotRules[index].MaxBuy
    let inputNum = e.detail.value
    if(inputNum.length === 0 || inputNum === '' || inputNum === null) {
      inputNum = 1
      wx.showToast({
        title: '最小购买数量为' + inputNum,
        icon: 'none',
      })
    }
    if(!reg.test(inputNum)) {
      wx.showToast({
        title: '请输入正确的购买数量',
        icon: 'none',
      })
      return
    }
    inputNum = Number(inputNum)
    if(inputNum > maxBuyNum) {
      inputNum = maxBuyNum
      wx.showToast({
        title: '最大购买数量为' + maxBuyNum,
        icon: 'none',
      })
    }
    list[pIndex].PromotRules[index].Multiple = inputNum
    _this.setData({
      cartlist: list,
      caculate_info: cart.caculate_info(list)
    })
    // 计算RuleType=5的商品总价
    _this.getGoodsTotalPrice(5)
    _this.packedChange(id,inputNum)
    // console.log('list>>>>', _this.data.cartlist)
  },
  buyNumberChange(e) {
    const _this = this
    let list = _this.data.cartlist
    let pIndex = e.currentTarget.dataset.pindex
    let index = e.currentTarget.dataset.index
    let type = e.currentTarget.dataset.type
    let id = e.currentTarget.dataset.id;
    let num = list[pIndex].PromotRules[index].Multiple
    let maxBuyNum = Number(list[pIndex].PromotRules[index].MaxBuy || 0);
    let min = 0;
    if(maxBuyNum!=0){
      if(min >= maxBuyNum){
        wx.showToast({
          title: '未满足最小起订量',
          icon: 'none',
        })
        return;
      }
    }
    if(type === 'reduce') {
      num > 1 ? num -= 1 : num = 1
      if(maxBuyNum!=0){
        if(num > maxBuyNum) {
          num = maxBuyNum
          wx.showToast({
            title: '最少购买' + maxBuyNum,
            icon: 'none',
          })
        }
      }
    }
    
    if(type === 'add') {
      num += 1
      // 判断购买数量是否大于最大购买数量
      if(maxBuyNum!=0){
        if(num > maxBuyNum) {
          num = maxBuyNum
          wx.showToast({
            title: '最大购买数量为' + maxBuyNum,
            icon: 'none',
          })
        }
      }
    }
    list[pIndex].PromotRules[index].Multiple = num
    _this.setData({
      cartlist: list,
      caculate_info: cart.caculate_info(list)
    })
    _this.getGoodsTotalPrice(5);
    _this.packedChange(id,num)
    
    // console.log('list>>>>', _this.data.cartlist)
  },
  // 更具RuleType计算商品总价
  getGoodsTotalPrice(type){
    let ruleType = 5
    if(type !== null && type === undefined && type === '') {
      ruleType = type
    }
    console.log("更具RuleType计算商品总价")
    const _this = this
    let list = _this.data.cartlist
    for(let i = 0; i < list.length; i++) {
      let child = list[i].PromotRules
      for(let j = 0; j < child.length; j++) {
        let count = 0
        if(child[j].RuleType === ruleType) {
          let product = child[j].Products
          for(let k = 0; k < product.length; k++) {
            let goods = product[k].Goods

            let itemCount = _this.getItemPrice(goods)
            count = Number(itemCount + count)
          }
          // console.log(count,'======1');
          child[j].singlePrice = count.toFixed(2)
          child[j].selfTotalPrice = (count * Number(child[j].Multiple)).toFixed(2)
          // child[j].selfTotalPrice = count.toFixed(2)
        }
      }
    }
    // console.log('list>>>>',list)
    _this.setData({
      cartlist: list
    })
  },
  getItemPrice(goods) {
    let count = 0
    console.log(goods)
    if(goods === null || goods.length <= 0) {
      return count
    }
    for(let i = 0; i < goods.length; i++) {
    
      if(goods[i].IsBuy==1){
        count += Number(goods[i].Quantity) * Number(goods[i].sale_price)
      }
    
    }
    return count
  },
  getGoodsNum(goods){
    let count = 0
    if(goods === null || goods.length <= 0) {
      return count
    }
    for(let i = 0; i < goods.length; i++) {
      if(goods[i].IsBuy==1){
      count += goods[i].Quantity
    }}
    return count
  },
  // 购物车，套装选中状态通知接口
  bindChecked(e){
    var that = this;
    let id = e.currentTarget.dataset.id
    var list = that.data.cartlist;
    // 1选中 0未选中
    var data = {PackedId:e.currentTarget.dataset.id,status:e.currentTarget.dataset.status==0?1:0}
    cart.packedChecked(data,function(content){
      for(let i = 0; i < list.length; i++) {
        let child = list[i].PromotRules
        for(let j = 0; j < child.length; j++) {
          if(child[j].RuleId == id){
            let flag = child[j].Checked === 0 ? 1 : 0
            child[j].Checked = flag
            let products = child[j].Products
            for(let k = 0; k < products.length; k++){
              let goods = products[k].Goods
              for(let l = 0; l < goods.length; l++){
                if(goods[l].IsBuy){
                goods[l].IsChecked = flag}
              }
            }
          }
        }
      }
      that.setData({
        caculate_info: cart.caculate_info(list),
        cartlist: list
      })
      that.set_select_all_status(that);
    })
  },
  // 购物车，套装数量修改通知接口
  packedChange(id,num){
    var data = {PackedId:id,AreaId:this.data.areaCode,Multiple:num};
    cart.packedChange(data,function(content){
    })
  },
  // 删除购物车中指定套装
  bindDel: function(e) {
    var that = this;
    clickIncrement(function() {
      cart.packedDelete(that.data.cartlist, e.currentTarget.dataset.id, that.data.CartName,function(content) {
        that.loadList();
      });
    });
  },
  /**
   * 点击选赠品
   * @param {*} e 
   */
  chooseProdcutGift(e) {
    let type = e.currentTarget.dataset.type
    let item = e.currentTarget.dataset.item
    let id = e.currentTarget.dataset.id
    let cartlist = this.data.cartlist || []
    let find = false
    let value = [-1, -1, -1, -1]
    if (type == 'rule') {
      let index1 = e.currentTarget.dataset.index1
      let index2 = e.currentTarget.dataset.index2
      value = [index1, index2]
    } else {
      // 通过循环获取当前点击的项
      // 由于页面代码过于复杂，不好为每个wx:for循环增加wx:for-index，所以需要在js中循环
      for (let i = 0; i < cartlist.length; i++) {
        let rule = cartlist[i] || {
          PromotRules: []
        }
        for (let j = 0; j < rule.PromotRules.length; j++) {
          let products = rule.PromotRules[j] || {
            Products: []
          }
          for (let k = 0; k < products.Products.length; k++) {
            let goods = products.Products[k] || {
              Goods: []
            }
            for (let x = 0; x < goods.Goods.length; x++) {
              if (goods.Goods[x].Id == item.Id && goods.Goods[x].RuleId == item.RuleId) {
                value = [i, j, k, x]
                find = true
              }
              if (find) {
                break
              }
            }
            if (find) {
              break
            }
          }
          if (find) {
            break
          }
        }
        if (find) {
          break
        }
      }
    }
    this.setData({
      chooseGiftIndex: value
    })
    router.navigate({
      path: 'chooseProductGift'
    })
  },
  /**
   * 重新计算商品信息
   * @param { Array } cartlist 购物车信息
   * @param { Number | String } cartItemId // 当前购物车项的id
   */
  resetProductInfo(cartlist = [], cartItemId = -1) {
    cartlist = cartlist.map((i) => {
      i.PromotRules = i.PromotRules || []
      i.PromotRules = i.PromotRules.map((j) => {
        j.Products = j.Products || []
        j.Products = j.Products.map((k) => {
          let Goods = deepClone(k.Goods) || []
          let ZeroStockBuy = k.ZeroStockBuy || 0 // 是否允许0库存下单
          let goodSet = {}
          let editThisProduct = false
          Goods.map((item, index) => {
            let id = item.GoodsId
            let {
              AuxQty,
              AuxRate,
              IsChecked
            } = item
            // 只有被选中的修改项才需要特价超限加购提示
            if (item.Id == cartItemId && IsChecked) {
              editThisProduct = true
            }
            let num = parseFloat(AuxQty) * parseFloat(AuxRate)
            if (!goodSet[id]) {
              goodSet[id] = {
                ExceedLimitOriginalPriceBuy: item.ExceedLimitOriginalPriceBuy, // 特价商品是否允许超限加购
                SBuyUpperLimit: item.SBuyUpperLimit,
                DiscountType: item.DiscountType, // 类型，2为特价
                count: IsChecked ? num : 0, // 商品规格所有已选择的单位数量之和
                list: [{
                  index,
                  item
                }]
              }
            } else {
              if (IsChecked) {
                goodSet[id].count += num
              }
              goodSet[id].list.push({
                index,
                item
              })
            }
          })
          for (let spec in goodSet) {
            // spec == GoodsId
            goodSet[spec].list.sort((a, b) => {
              return a.item.AuxRate - b.item.AuxRate
            })
            let {
              ExceedLimitOriginalPriceBuy,
              DiscountType,
            } = goodSet[spec]
            goodSet[spec].panicCount = 0
            goodSet[spec].normalCount = 0
            if (goodSet[spec].count > goodSet[spec].SBuyUpperLimit && (DiscountType == 2 && ExceedLimitOriginalPriceBuy == 1)) {
              // 只有编辑商品数量时才弹窗提示特价商品超限加购信息
              if (editThisProduct) {
                alert(`限优惠${goodSet[spec].SBuyUpperLimit}${k.AuxUnit || k.Unit || ''},超出限购部分按原价结算`)
              }
              goodSet[spec].panicCount = goodSet[spec].SBuyUpperLimit
              goodSet[spec].normalCount = goodSet[spec].count - goodSet[spec].SBuyUpperLimit
            } else {
              goodSet[spec].panicCount = goodSet[spec].count
            }
            // 第二次循环，用于重设特价商品超限加购后的价格
            // 需要显示超限部分和商品原价部分的均价
            goodSet[spec].list.map(data => {
              let item = data.item
              let index = data.index
              let {
                BuyUpperLimit,
                SBuyUpperLimit,
                BuyLowerLimit,
                Stock,
                SStock,
                AuxQty,
                AuxRate,
                AuxUnit,
                UnitPrices,
              } = item
              AuxQty = parseFloat(AuxQty)
              AuxRate = parseFloat(AuxRate)
              let itemCount = precisionX(AuxQty, AuxRate) // 当前单位换算为基础单位数量
              if (ZeroStockBuy > 0 || (Stock >= BuyUpperLimit && SBuyUpperLimit > 0)) {
                if (DiscountType == 2 && ExceedLimitOriginalPriceBuy == 1) {
                  if (ZeroStockBuy > 0) {
                    // 允许库存下单，则设置为一个大数
                    item.max = 99999999
                  } else {
                    // 特价商品并且允许超库存下单
                    item.max = Stock
                  }
                } else {
                  if (BuyUpperLimit > 0) {
                    item.max = BuyUpperLimit
                  } else {
                    item.max = 0
                  }
                }
              } else {
                if (Stock > 0) {
                  item.max = Stock
                } else {
                  item.max = 0
                }
              }
              item.min = BuyLowerLimit
              if (item.IsChecked) {
                let originPrice = -1
                let salesPrice = -1
                try {
                  originPrice = UnitPrices[AuxRate][0].CostPrice
                  salesPrice = UnitPrices[AuxRate][0].Price
                } catch (error) {
                  console.log('获取原价格失败')
                }
                if (goodSet[spec].panicCount >= itemCount) {
                  // 全为特价商品，无需处理再重新计算价格
                  goodSet[spec].panicCount -= itemCount
                } else if ((itemCount - goodSet[spec].panicCount) > 0) {
                  // 部分为特价商品，部分为超出特价部分的商品（需要计算新的平均价格）
                  let n1 = goodSet[spec].panicCount // 特价部分数量
                  let n2 = calulateReduce(itemCount, goodSet[spec].panicCount) // 原价部分数量
                  if (isEmpty(salesPrice)) {
                    salesPrice = 0
                  }
                  if (isEmpty(originPrice)) {
                    originPrice = 0
                  }
                  let p1 = precisionX(n1, salesPrice) // 特价部分的总价
                  let p2 = precisionX(n2, originPrice) // 原价部分的总价
                  let pt = calulateAdd(p1, p2) // 当前单位总价格
                  let averagePrice = precisionDiv(pt, itemCount) // 平均价格
                  item.sale_price = averagePrice
                  goodSet[spec].panicCount = 0
                } else {
                  // 全为超出特价部分商品，显示原价
                  if (originPrice != -1) {
                    item.sale_price = originPrice
                  }
                }
              }
              Goods[index] = item
            })
          }
          k.Goods = Goods
          return k
        })
        return j
      })
      return i
    })

    console.log(cartlist)
    return cartlist
  },
})